package cn.wangkai.peanut.dao.auth;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.htmlparser.lexer.InputStreamSource;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cn.wangkai.peanut.bean.auth.AccessToken;
import cn.wangkai.peanut.bean.auth.LoginUser;
import cn.wangkai.peanut.util.Auth.AuthConfig;
import cn.wangkai.peanut.util.Auth.AuthUtil;

public class AuthUserManagerImp implements AuthUserManager {
	private static final Log log = LogFactory.getLog(AuthUserManagerImp.class);
	public static String CLIENTSESSIONUID="ff7f9d875016452397b28af9ce71ee63";
	private static String AuthURL;
	static{
		AuthURL = AuthConfig.getValue("AuthURL");
		if(StringUtils.isBlank(AuthURL)) AuthURL = "http://localhost:8080/AuthUser/";
	}
	public AuthUserManagerImp() {
	}
	
	/**
	 * 通过URL和参数获取Json对象
	 * @param url
	 * @param parames
	 * @return
	 * @throws AuthManagerException
	 */
	private JSONObject getUrlJson(String url,String parames) throws AuthManagerException{
		JSONObject $json = new JSONObject();
		String json;
		try {
			json = getContentByIE(url,parames);
			if(json==null) return null;
			$json =JSONObject.parseObject(json);
			if($json.containsKey("msg")||$json.containsKey("succees")){
				if(!$json.getBoolean("succees")){
					log.error($json);
					throw new AuthManagerException($json.getString("msg"));
				}
			}
		} catch (MalformedURLException e) {
			log.error(e);
			throw new AuthManagerException("URL格式或参数错误！",e);
		} catch (IOException e) {
			log.error(e);
			throw new AuthManagerException("网络连接失败！",e);
		}
		return $json;
	}
	
	/**
	 * 通过URL和参数获取JSONArray对象
	 * @param url
	 * @param parames
	 * @return
	 * @throws AuthManagerException
	 */
	private JSONArray getUrlJsonlist(String url,String parames) throws AuthManagerException{
		JSONArray $json = new JSONArray();
		String json;
		try {
			json = getContentByIE(url,parames);
			if(json==null) return null;
			$json = JSONArray.parseArray(json);
		} catch (MalformedURLException e) {
			log.error(e);
			throw new AuthManagerException("URL格式或参数错误！",e);
		} catch (IOException e) {
			log.error(e);
			throw new AuthManagerException("网络连接失败！",e);
		}
		return $json;
	}
	
	public AccessToken access_token(String client_id) throws AuthManagerException{
		String url = AuthURL+"auth/access_token.xwy";
		if(client_id==null){//如果没有客户端码，重新生成
			client_id = AuthUtil.getGUID();
		}
		String parames = "client_id="+client_id;
		JSONObject $json= getUrlJson(url,parames);
		return new AccessToken($json);
	}
	
	
	public LoginUser login(AccessToken token,String LoginID,String Password) throws AuthManagerException{
		String url = AuthURL+"authUser/login.xwy";
		//判断本地是否有ClientID
		if(StringUtils.isBlank(token.getClient_id())||StringUtils.isBlank(token.getAccess_token())){//如果没有客户端码，重新生成
			throw new AuthManagerException("验证信息不完整!");
		}
		String parames = "client_id="+token.getClient_id();		//客户唯一码
		parames += "&access_token="+token.getAccess_token();	//服务器验证码
		parames += "&user_login="+LoginID;						//登录用户名
		parames += "&user_password="+Password;					//登录密码
		JSONObject $json= null;
		try{
			$json = getUrlJson(url,parames);
		}catch (AuthManagerException e) {
			log.error(e);
			throw new AuthManagerException(e);
		}
		return new LoginUser($json);
	}
	
	/**
	 * 用户退出登录
	 * 
	 * @param token
	 * @param LoginID
	 * @param Password
	 * @return
	 * @throws AuthManagerException
	 * @throws AuthManagerException
	 */
	public boolean loginout(AccessToken token,String LoginID,String Password) throws AuthManagerException{
		String url = AuthURL+"authUser/loginout.xwy";
		//判断本地是否有ClientID
		if(StringUtils.isBlank(token.getClient_id())||StringUtils.isBlank(token.getAccess_token())){//如果没有客户端码，重新生成
			throw new AuthManagerException("验证信息不完整!");
		}
		String parames = "client_id="+token.getClient_id();		//客户唯一码
		parames += "&access_token="+token.getAccess_token();	//服务器验证码
		JSONObject $json= null;
		try{
			$json = getUrlJson(url,parames);
		}catch (AuthManagerException e) {
			log.error(e);
			throw new AuthManagerException(e);
		}
		if(!$json.getBoolean("succees"))
			throw new AuthManagerException($json.getString("msg"));
		else
			return true;
	}
	
	
	public JSONArray menu(AccessToken token) throws AuthManagerException{
		String url = AuthURL+"authUser/usermenu.xwy";
		//判断本地是否有ClientID
		if(StringUtils.isBlank(token.getClient_id())||StringUtils.isBlank(token.getAccess_token())){//如果没有客户端码，重新生成
			throw new AuthManagerException("验证信息不完整!");
		}
		String parames = "client_id="+token.getClient_id();		//客户唯一码
		parames += "&access_token="+token.getAccess_token();	//服务器验证码
		JSONArray $json= getUrlJsonlist(url,parames);
		return $json;
	}
	
	public String getContentByIE(String URLstr,String params) throws MalformedURLException,IOException {
		//http://localhost:8080/AuthUser/auth/access_token.xwy?client_id=ff7f9d875016452397b28af9ce71ee63
		System.setProperty("sun.net.client.defaultConnectTimeout","3000");
		System.setProperty("sun.net.client.defaultReadTimeout","3000");
        URL url = new URL(URLstr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");// 提交模式 
        // conn.setConnectTimeout(10000);//连接超时 单位毫秒 
        // conn.setReadTimeout(2000);//读取超时 单位毫秒 
        conn.setDoOutput(true);// 是否输入参数
        byte[] bypes = params.getBytes();
        conn.getOutputStream().write(bypes);// 输入参数 
        InputStream inStream=conn.getInputStream();
		return inputStream2String(inStream,"UTF-8").toString();
}
	
	@SuppressWarnings("resource")
	private StringBuffer inputStream2String(InputStream is,String Encoding) throws IOException {
		BufferedReader in = new BufferedReader(new InputStreamSource(is,Encoding));
		StringBuffer bodybuffer = new StringBuffer();
		String line = "";
		while ((line = in.readLine()) != null) {
			bodybuffer.append(line + "\n");
		}
		return bodybuffer;
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		AuthUserManager test = new AuthUserManagerImp();
		try {
			AccessToken token = test.access_token("ff7f9d875016452397b28af9ce71ee63");
			System.out.println(token.getAccess_token());
			System.out.println(token.getAccess_time());
			System.out.println(token.isSuccees());
			LoginUser user = test.login(token, "admin", "admin");
			System.out.println(JSONObject.toJSONString(user));
			System.out.println(user.getright("SYS_ADMIN"));
			System.out.println(user.getright("SYS_ADMIN1"));
			System.out.println(test.menu(token));
		} catch (AuthManagerException e) {
			e.printStackTrace();
		}
		
	}

}
